package com.j1ay.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.j1ay.forum.dao.mapper.RoleMapper;
import com.j1ay.forum.model.pojo.po.Role;
import com.j1ay.forum.model.pojo.po.Type;
import com.j1ay.forum.model.pojo.po.User;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.model.pojo.vo.Result;
import com.j1ay.forum.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author J1ay
 * @Date 2021/12/25 21:59
 * @Description
 */

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired(required = false)
    private RoleMapper roleMapper;

    /**
     * 获取所有角色列表
     * @return
     */
    @Override
    public Result getRoleList() {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        // 先按置顶排序，再按创建的时间倒序排序
        queryWrapper.eq(Role::getDelFlag, 0);
        List<Role> roles = roleMapper.selectList(queryWrapper);

        return Result.success(roles);
    }

    @Override
    public Result delete(Long id) {
        if (null == id) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        int res = this.roleMapper.deleteById(id);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        return Result.success(null);
    }

    @Override
    public Result add(Role role) {
        if (StringUtils.isBlank(role.getRoleName())) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        int res = this.roleMapper.insert(role);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        return Result.success(null);
    }

    @Override
    public Result update(Role role) {
        if (null == role.getId()) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        int res = this.roleMapper.updateById(role);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        return Result.success(null);
    }
}
